<?php


namespace app\admin\controller;


use app\common\model\ExpressModel;
use app\common\model\MoneyLogModel;
use app\common\model\OrderModel;
use app\common\model\OrderReceiptModel;
use app\common\model\StorageManageModel;
use app\common\model\StorageModel;
use cmf\controller\AdminBaseController;
use GuzzleHttp\Client;
use kdapi\Eorder;
use kdapi\Eprint;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\db\Query;
use think\Request;

class OrderController extends AdminBaseController
{
    public function index()
    {
        $param = $this->request->param();
        $list = OrderModel::where(
            function (Query $query) use ($param) {
                if (!empty($param['keyword'])) {
                    $query->where('user_id|order_no|order_name', 'like', "%{$param['keyword']}%");
                }
                if (isset($param['order_status']) && $param['order_status'] > -1) {
                    $query->where('order_status', $param['order_status']);
                }
            })->order('id desc')->paginate()
            ->each(function ($v, $k) {
                $v['cn_status'] = OrderModel::getStatus($v['order_status']);
            });
        $this->assign('status', OrderModel::getStatus());
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function detail($id)
    {
        $data = OrderReceiptModel::where('id', $id)->find();
        $this->assign('stat', OrderReceiptModel::getStatus());
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function receipt()
    {
        $param = $this->request->param();
        $list = OrderReceiptModel::where(
            function (Query $query) use ($param) {
                $query->where('show_status', 1);
                if (!empty($param['keyword'])) {
                    $query->where('obtain_order_no|self_order_no', "{$param['keyword']}");
                }
                if (isset($param['order_status']) && $param['order_status'] > -1) {
                    $query->where('order_status', $param['order_status']);
                }

                if (!empty($param['order_id'])) {
                    $query->where('order_id', $param['order_id']);
                }

            })->order('id desc')->paginate()
            ->each(function ($v, $k) {

            });
        $this->assign('status', OrderReceiptModel::getStatus());
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function unreceipt()
    {
        $param = $this->request->param();
        $list = OrderReceiptModel::where(
            function (Query $query) use ($param) {
                $query->where('show_status', 1)->where('order_status', 0);
                if (!empty($param['keyword'])) {
                    $query->where('obtain_order_no|self_order_no', "{$param['keyword']}");
                }
                if (isset($param['order_status']) && $param['order_status'] > -1) {
                    $query->where('order_status', $param['order_status']);
                }

                if (!empty($param['order_id'])) {
                    $query->where('order_id', $param['order_id']);
                }

                $time = time() - 7200;
                $query->where('add_time', '<', $time);

                $query->whereNull('delivery_no');

            })->order('id desc')->paginate()
            ->each(function ($v, $k) {
                $v['manage_name'] = $v['mid'] == 0 ? '平台' : StorageManageModel::where('id', $v['id'])->value('name');
            });
        $this->assign('status', OrderReceiptModel::getStatus());
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function cancel($id)
    {
        $receipt = OrderReceiptModel::where('id', $id)->find();
        if (!$receipt || $receipt['show_status'] != 1 || $receipt['order_status'] != 0 || !empty($receipt['delivery_no'])) {
            $this->error('包裹数据异常或者不支持取消');
        }

        Db::startTrans();
        if ($receipt['mid'] == 1) {
            $manage = StorageManageModel::find(1);
            $client = new Client();
            try {
                $resp = $client->request('post', 'https://www.lipindao.com/api/goods/calloff', [
                    'headers'     => ['token' => $manage['token']],
                    'form_params' => [
                        'ids' => $receipt['taskid']
                    ]
                ]);

                $contents = ($resp->getBody()->getContents());
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $data = json_decode($contents, true);
            if ($data['code'] == 1) {

            } else {
                Db::rollback();
                $this->error($manage['name'] . '：' . $data['msg']);
            }
        }

        $res = MoneyLogModel::addLog($receipt['user_id'], $receipt['total_price'], 4, '订单后台取消', $receipt['id']);
        if (!$res) {
            Db::rollback();
            $this->error(MoneyLogModel::getErrorInfo());
        }

        if (!$receipt->save(['refund_time' => time(), 'order_status' => 3])) {
            Db::rollback();
            $this->error('包裹记录更新失败');
        }

        Db::commit();
        $this->success('取消成功');
    }

    public function express(Request $request)
    {
        $param = $request->param();
        $receipt = OrderReceiptModel::where('id', $param['id'])->find();
        if ($request->isPost()) {
            if (empty($param['delivery_no'])) {
                $this->error('快递单号不能为空');
            }

            list($delivery_code, $delivery_company) = explode('-', $param['delivery']);
            unset($param['delivery']);
            $param['delivery_code'] = $delivery_code;
            $param['delivery_company'] = $delivery_company;
            $param['delivery_time'] = time();
            $param['order_status'] = 1;
            $param['delivery_no'] = 1;
            if ($receipt->save($param)) {
                $this->success('发货完成', '/admin/order/detail?id=' . $param['id']);
            } else {
                $this->error('发货失败');
            }
        }
        if ($receipt->order_status != 0) {
            $this->error('当前包裹状态不能发货');
        }

        $express = ExpressModel::getExpress();
        $this->assign('express', $express);
        $this->assign('data', $receipt);
        return $this->fetch();
    }

    public function excel(Request $request)
    {
        $this->success('下载中。。。', url('/appapi/index/excel', $request->param()));
    }

    public function refund(Request $request)
    {
        $data = OrderReceiptModel::where('id', $request->id)->find();
        if ($data['mid'] == 1) {
            $manage = StorageManageModel::find($data['mid']);
            $client = new Client();
            try {
                $resp = $client->request('post', 'https://www.lipindao.com/api/goods/calloff', [
                    'headers'     => ['token' => $manage['token']],
                    'form_params' => [
                        'ids' => $data['taskid']
                    ]
                ]);

                $contents = ($resp->getBody()->getContents());
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $data = json_decode($contents, true);
            if ($data['code'] == 1) {
                $data->save(['taskrefund' => 1]);
            } else {
                $this->error('第三方订单取消失败：' . json_encode($data));
            }
        }

        $rs = MoneyLogModel::addLog($data->user_id, $data->total_price, 4, '包裹退款', $data->order_no);
        if (!$rs) {
            $this->error(MoneyLogModel::getErrorInfo());
        }
        $data->save(['order_status' => 3, 'refund_handle_time' => time()]);

        $this->success('退款成功');
    }


    public function unrefund(Request $request)
    {
        $data = OrderReceiptModel::where('id', $request->id)->find();
        $data->save(['order_status' => 4, 'refund_handle_time' => time()]);
        $this->success('操作成功');
    }

    public function setexcel()
    {
        return $this->fetch();
    }

    public function batch_express(Request $request)
    {
        $param = $request->param();
        $list = [];
        if ($request->isPost() && $param['step'] == 1) {
            $excel_path = WEB_ROOT . 'upload/' . $param['file'];
            if (!file_exists($excel_path)) {
                $this->error('文件不存在，上传失败');
            }
            $excel_type = ucfirst(explode('.', $excel_path)[1]);
            $reader = IOFactory::createReader($excel_type);
            $phpExcel = $reader->load($excel_path);
            $sheet = $phpExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow();
            $highestColumn = $sheet->getHighestColumn();

            if ($highestColumn == 'C') {
                for ($row = 2; $row <= $highestRow; $row++) {
                    $list[] = [
                        'obtain_order_no'  => $sheet->getCell('A' . $row)->getValue(),
                        'delivery_company' => $sheet->getCell('B' . $row)->getValue(),
                        'delivery_no'      => $sheet->getCell('C' . $row)->getValue(),
                    ];
                }
            } else {
                $this->error('模板不合符规则，请确认模板只有订单号、快递公司和快递单号三列后再重新上传');
            }

            if (empty($list)) {
                $this->error('文件内容为空！');
            }
        }

        if ($request->isPost() && $param['step'] == 2) {
            $data = $param['data'];
            if (empty($data)) {
                $this->error('没有发货数据了');
            }
            $error = [];
            foreach ($data as $item) {
                $info = OrderReceiptModel::where(['obtain_order_no' => $item['obtain_order_no'], 'show_status' => 1])->find();
                if (!$info || $info['order_status'] != 0) {
                    $error[] = ['data' => $item, 'msg' => '包裹不存在或包裹状态异常'];
                    continue;
                }
                $order = OrderModel::where('id', $info['order_id'])->find();
                if (!$order || $order['order_status'] != 2) {
                    $error[] = ['data' => $item, 'msg' => '订单不存在或订单状态异常'];
                    continue;
                }
                $item['order_status'] = 1;
                $item['delivery_time'] = time();
                $item['delivery_type'] = 2;
                if (!$info->save($item)) {
                    $error[] = ['data' => $item, 'msg' => '发货失败'];
                    continue;
                }
            }
            $this->success('success', '', compact('error'));
        }

        $this->assign('list', $list);
        return $this->fetch();
    }

    public function batch_express_auto()
    {
        $list = [];
        $this->assign('storage', StorageModel::all());
        $param = $this->request->param();

        if (isset($param['store_id']) && $param['store_id'] > 0) {
            $list = OrderReceiptModel::where(
                function (Query $query) use ($param) {
                    $query->where('show_status', 1)
                        ->where('order_status', 0)
                        ->where('storage_id', $param['store_id']);

                })->order('id desc')->paginate();
            $this->assign('status', OrderReceiptModel::getStatus());

        } elseif (isset($param['step']) && $param['step'] == 2) {
            if (empty($param['ids'])) {
                $this->error('选择要发货的包裹');
            }

            $express_settings = cmf_get_option('express_settings');
            foreach ($param['ids'] as $id) {
                $res = Eorder::order($id);
                if (isset($res['Success']) && $res['Success'] == true) {
                    $data = [
                        'delivery_code' => $express_settings['Code'],
                        'delivery_no'   => $res['Order']['LogisticCode'],
                        'delivery_com'  => $express_settings['Name'],
                        'delivery_time' => time(),
                        'delivery_type' => 3,//自动批量发货
                        'order_status'  => 1
                    ];
                    OrderReceiptModel::update($data, ['id' => $id]);
                } else {
                    $this->error(json_encode($res));
                }
            }
        }

        $this->assign('list', $list);
        return $this->fetch();
    }

    public function eprint()
    {
        $this->assign('storage', StorageModel::all());
        $param = $this->request->param();
        if ($this->request->isPost()) {
            if (empty($param['ids'])) {
                $this->error('选择要打单的包裹');
            }

            if (empty($param['port_name'])) {
                $this->error('填写打印机名称');
            }

            $res = (new Eprint())->build_form($param['ids'], $param['port_name']);
            if (!$res) {
                $this->success('ok');
            } else {
                $this->error('打单失败');
            }
        }
        $list = OrderReceiptModel::where(
            function (Query $query) use ($param) {
                $query->where('show_status', 1)->where('delivery_type', 3);
                if (!empty($param['store_id'])) {
                    $query->where('storage_id', $param['store_id']);
                }
            })->order('id desc')->paginate()
            ->each(function ($v, $k) {
                $v['storage'] = StorageModel::find($v['storage_id']);
            });
        $this->assign('status', OrderReceiptModel::getStatus());
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function doc()
    {
        return $this->fetch();
    }

    public function del($id)
    {
        if (OrderModel::destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function Redel($id)
    {
        if (OrderReceiptModel::destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function batchdel($ids)
    {
        if (OrderModel::destroy($ids)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function recbatchdel($ids)
    {
        if (OrderReceiptModel::destroy($ids)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function changestatus($id, $status)
    {
        if (OrderModel::update(['id' => $id, 'order_status' => $status])) {
            $this->success('success');
        } else {
            $this->error('失败');
        }
    }


}